package com.example.demo.redis.util;

import com.example.demo.redis.RedissonConstants;
import com.example.demo.redis.able.CacheInterface;
import com.example.demo.redis.able.LockInterface;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RExpirable;
import org.redisson.api.RLock;
import org.springframework.util.StringUtils;

@Slf4j
public class RedissonUtils {

/**
     * 获取缓存key
     */

    public static String getCacheKey(CacheInterface cacheInterface, String... keys) {
        String cacheKey = cacheInterface.getKey();
        if (StringUtils.hasLength(cacheInterface.getNamespace())) {
            cacheKey = cacheInterface.getNamespace().concat(RedissonConstants.SEPARATOR).concat(cacheKey);
        }
        String key = buildKey(keys);
        if (!StringUtils.hasLength(key)) {
            return cacheKey;
        }
        if (cacheInterface.getKey().endsWith(RedissonConstants.SEPARATOR)) {
            cacheKey = cacheKey.concat(key);
        } else {
            cacheKey = cacheKey.concat(RedissonConstants.SEPARATOR).concat(key);
        }
        return cacheKey;
    }

/**
     * 构建缓存key
     */

    public static String buildKey(String... keys) {
        String cacheKey = null;
        if (keys == null || keys.length <= 0) {
            return cacheKey;
        }

        for (String key : keys) {
            if (StringUtils.hasLength(cacheKey)) {
                cacheKey = cacheKey.concat(RedissonConstants.SEPARATOR).concat(key);
            } else {
                cacheKey = key;
            }
        }
        return cacheKey;
    }

/**
     * 设置缓存过期时间
     */

    public static boolean expire(RExpirable rExpirable, CacheInterface cacheInterface) {
        return rExpirable.expire(cacheInterface.getExpire(), cacheInterface.getUnit());
    }

/**
     * 尝试加锁
     */

    public static boolean tryLock(RLock rLock, LockInterface lockInterface) {
        try {
            return rLock.tryLock(lockInterface.getWaitTime(), lockInterface.getExpire(), lockInterface.getUnit());
        } catch (InterruptedException e) {
            log.error(" tryLock error, lock:{}", rLock.getName(), e);
        }
        return false;
    }


}
